<!-- 自定义模块 -->
<template>
  <div class="diy_mod">
    <!-- 模块列表 -->
    <el-row>
      <el-col>
        已有模块：
        <el-tag v-for="(o,i) in list" :class="{ active: form.table_id === o.table_id }" :key="i" :disable-transitions="false"
          @click="get_table(o.table_id)" @close="del_table(o)" closable>{{o.title}}</el-tag>
        <el-autocomplete popper-class="my-autocomplete" ref="form" style="width: 150px;" v-model="form.title"
          :fetch-suggestions="tableSearch" @select="handleSelect" placeholder="模块名" @blur="set_name2()">
          <template slot-scope="{ item }">
            <span class="title">{{ item.title }}</span>
          </template>
        </el-autocomplete>

        <el-input v-model="form.name" ref="form" style="width: 150px;" placeholder="表名" @blur="set_name()">
        </el-input>
        <el-button type="primary" @click="auto_field()">智能匹配</el-button>
        <el-button type="primary" @click="save_mod()">保存模块</el-button>
        <el-checkbox style="margin-left: 0.5rem;" v-model="attr.only_me">仅查我</el-checkbox>
        <el-checkbox style="margin-left: 0.5rem;" v-model="attr.is_user_table">用户表</el-checkbox>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="24">
        <diy_panel :obj="attr"></diy_panel>
      </el-col>
      <el-col :span="24">
        <diy_field :list="list_field" :field_defult="field_defult"></diy_field>
      </el-col>
      <el-col :span="24">
        <el-button style="width: 50%; display: block; margin: 2rem auto;" type="primary" @click="save_mod()">保存模块</el-button>
      </el-col>
    </el-row>

    <!-- 删除表弹窗 -->
    <el-dialog title="删除模块" :visible.sync="show">
      <span>是否删除</span><strong> {{ query_del.title }} </strong><span>表?</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="show = false">取 消</el-button>
        <el-button type="primary" @click="show = false; del({  table_id: query_del.table_id } )">确 定</el-button>
      </span>
    </el-dialog>

    <div class="float_box" id="float_box" v-drag>
      <h5 class="center">参考字段</h5>
      <el-collapse v-model="activeNames" @change="get_field2" :accordion="true">
        <el-collapse-item v-for="(o, i) in list" :title="o.title" :name="o.table_id" :key="o.name">
          <div class="item" v-for="(oj, n) in list_field_refer" :key="oj.name + n">{{ oj.title }} <i class="el-icon-plus fr"
              @click="set_field2(oj)"></i></div>
        </el-collapse-item>
      </el-collapse>
    </div>
  </div>
</template>

<script>
  import mixin from "@/mixins/component.js";
  import diy_field from '@/components/diy_field.vue';
  import diy_panel from "./diy_panel.vue";

  export default {
    mixins: [mixin],
    components: {
      diy_panel,
      diy_field
    },
    props: {
      order_id: {
        type: Number,
        default: 0
      }
    },
    data() {
      return {
        url_get_list: "~/apis/dev/order_table?",
        url_set: "~/apis/dev/order_table?method=set",
        url_del: "~/apis/dev/order_table?method=del",
        query: {
          order_id: this.order_id,
          page: 0,
          size: '0'
        },
        form: {
          order_id: this.order_id,
          table_id: 0,
          title: "",
          name: ""
        },
        title: "",
        attr: {
          "list_page": "有列表",
          "register_page": "无",
          "examine": "无",
          "pay": "无",
          "recommend": "无",
          "to_page": "无",
          "time_type": "无",
          "frequency": "无",
          "figure": "无",
          "cart_page": "无",
          "add_page": "无",
          "details_page": "有详情",
          "sign_page": "无",
          "comment": false,
          "score": false,
          "location": false,
          "click_num": false,
          "export_db": false,
          "import_db": false,
          "if": "",
          "compute": "",
          "table": "",
          "table_nav_name": "",
          "read_from_user": "",
          "show_home": false,
          "integral": false,
          "praise": false,
          "collect": false,
          "print": false,
          "seat": false,
          "only_me": false,
          "is_user_table": false
        },
        attr_defult: {
          "list_page": "有列表",
          "register_page": "无",
          "examine": "无",
          "pay": "无",
          "recommend": "无",
          "to_page": "无",
          "time_type": "无",
          "frequency": "无",
          "figure": "无",
          "cart_page": "无",
          "add_page": "无",
          "details_page": "有详情",
          "sign_page": "无",
          "comment": false,
          "score": false,
          "location": false,
          "click_num": false,
          "export_db": false,
          "import_db": false,
          "if": "",
          "compute": "",
          "table": "",
          "table_nav_name": "",
          "read_from_user": "",
          "show_home": false,
          "integral": false,
          "praise": false,
          "collect": false,
          "print": false,
          "seat": false,
          "only_me": false,
          "is_user_table": false
        },
        obj_defult: {
          order_id: this.order_id,
          table_id: 0,
          title: "",
          name: ""
        },
        list_field: [{
          "field_id": 0,
          "table_id": 0,
          "name": "",
          "title": "",
          "type": "",
          "drop_down_table": "",
          "drop_down_field": "",
          "drop_down_diy": "",
          "from_user_table": "",
          "unique": "",
          "can_sort": 0,
          "can_query": 0,
          "is_type_show": 0,
          "user_group": "",
          "display": 100,
          "session_read": 0,
          "compute": "",
          "tip_start": "",
          "tip_way": "",
          "tip_end": "",
          "count_chart": "",
          "is_img_list": 0,
          "is_show_collect": 0,
          "description": ""
        }],
        field_defult: {
          "field_id": 0,
          "table_id": 0,
          "name": "",
          "title": "",
          "type": "",
          "drop_down_table": "",
          "drop_down_field": "",
          "drop_down_diy": "",
          "from_user_table": "",
          "unique": "",
          "can_sort": 0,
          "can_query": 0,
          "is_type_show": 0,
          "user_group": "",
          "display": 100,
          "session_read": 0,
          "compute": "",
          "tip_start": "",
          "tip_way": "",
          "tip_end": "",
          "count_chart": "",
          "is_img_list": 0,
          "is_show_collect": 0,
          "description": ""
        },
        // 删除
        query_del: {},
        // 所有表名，用于模块快速起名
        all_table: [],
        // 折叠选中名
        activeNames: "",
        // 参考字段列表
        list_field_refer: []
      }
    },
    methods: {
      /**
       * 保存名字
       */
      set_name2() {
        var form = this.form;
        if (form.title) {
          this.$translate(form.title, function(name) {
            form.name = name;
          });
        }
      },
      /**
       * 保存名字
       */
      set_name() {
        var form = this.form;
        if (!form.name && form.title) {
          this.$translate(form.title, function(name) {
            form.name = name;
          });
        }
      },
      /**
       * 删除表
       * @param {Object} query_del 查询条件
       */
      del_table(query_del) {
        this.query_del = query_del;
        if (this.query_del.table_id === this.form.table_id) {
          this.$toast('无法删除编辑中的表！请先切换到其他表再删除！', 'danger');
          return
        }
        this.show = true;
      },
      /**
       * 事件 - 删除表之后删除表相关的字段
       */
      del_after() {
        this.$get("~/apis/dev/order_field?method=del&table_id=" + this.query_del.table_id);
        this.get_list();
      },
      /**
       * 保存字段
       * @param {Number} table_id 表ID
       */
      set_field(table_id) {
        var list = this.list_field;
        for (var i = 0; i < list.length; i++) {
          var o = list[i];
          if (o.title) {
            o.table_id = table_id;
            o.display = i + 1;
            if (o.field_id) {
              this.$post("~/apis/dev/order_field?method=set&field_id=" + o.field_id, o);
            } else {
              this.$post("~/apis/dev/order_field?method=add&", o);
            }
          }
        }
        this.list_field = [Object.assign({}, this.field_defult)]
      },
      /**
       * 成功后的操作
       * @param {Number} table_id
       */
      success_action(table_id) {
        this.$toast('保存成功', 'success');
        this.set_field(table_id);
        this.get_list();
        this.attr = Object.assign({}, this.attr_defult);
        this.form = Object.assign({}, this.obj_defult);
      },
      /**
       * 修改表
       * @param {Object} body 要修改的键值
       */
      set_table(body) {
        var _this = this;
        this.$post("~/apis/dev/order_table?method=set&table_id=" + body.table_id, body, function(json) {
          if (json.result) {
            var bl = json.result.bl;
            if (bl) {
              _this.success_action(body.table_id)
            } else {
              _this.$toast(json.result.tip, 'danger');
            }
          } else if (json.error) {
            _this.$toast(json.error.message, 'danger');
          } else {
            _this.$toast('服务器请求失败！');
          }
        });
      },
      /**
       * 保存模块
       */
      save_mod() {
        var _this = this;
        var form = this.form;
        if (!form.name || !form.title) {
          this.$toast('表名和字段名不能为空！', 'danger');
          return;
        }
        if (form.name.length < 2) {
          this.$toast('表名最少两个字符', 'danger');
          return;
        }
        if (!/[a-zA-Z]+[a-zA-Z0-9_]+[a-zA-Z0-9]+/gi.test(form.name)) {
          this.$toast('表名只能是英文字母开头，且只能由“英文、数字、_”组成', 'danger');
          return;
        }
        if (form.title.length < 2) {
          this.$toast('模块名最少两个字符', 'danger');
          return;
        }
        if (!/[\u4e00-\u9fa5a-zA-Z]+[\u4e00-\u9fa5a-zA-Z0-9]+/gi.test(form.title)) {
          this.$toast('模块名不能含特殊字符, 且不能为数字开头', 'danger');
          return;
        }
        if (this.list_field.length < 2) {
          this.$toast('表字段不能为空！');
          return;
        }
        form.order_id = this.query.order_id;
        var msg = "";
        var lt = this.list_field;
        var dict_title = {};
        var dict_name = {};
        // 判断图列的对象
        var img_obj = {
          img: "",
          title: ""
        };

        for (var i = 0; i < lt.length - 1; i++) {
          var o = lt[i];
          if (!o.title) {
            msg = "字段名不能为空!";
            break;
          } else if (dict_title[o.title]) {
            msg = "字段不能相同!";
            break;
          } else if (dict_name[o.name]) {
            msg = "字段名不能相同!";
            break;
          } else {
            dict_title[o.title] = true;
            dict_name[o.name] = true;
            if (!o.type) {
              o.type = "文本"
            }
            if (o.is_img_list) {
              if (o.type === "图片") {
                img_obj.img = o.title;
              } else if (o.type === "文本") {
                img_obj.title = o.title;
              }
            }
          }
        }

        if (this.attr.list_page.indexOf("图") !== -1) {
          if (!img_obj.img) {
            msg = "列表带图列时，图片是必须的";
          } else if (!img_obj.title) {
            msg = "列表带图列时，标题是必须的";
          }
        }

        if (msg) {
          this.$toast(msg, 'danger');
          return
        }
        form.config = JSON.stringify(this.attr);

        if (form.table_id) {
          this.set_table(form);
        } else {
          var obj = this.list.getObj({
            name: form.name,
            title: form.title
          });
          if (obj) {
            this.set_table(this.form);
          } else {
            obj = this.list.getObj({
              name: form.name
            });
            if (obj) {
              this.$toast('表名已存在！', 'danger');
            } else {
              obj = this.list.getObj({
                title: form.title
              });
              if (obj) {
                this.$toast('模块名已存在！', 'danger');
              } else {
                this.$post("~/apis/dev/order_table?method=add", this.form, function(json) {
                  if (json && json.result) {
                    var bl = json.result.bl;
                    if (bl) {
                      _this.$get("~/apis/dev/order_table?method=get&field=table_id", {
                        title: _this.form.title,
                        order_id: _this.form.order_id
                      }, function(jobj) {
                        if (jobj.result && jobj.result.list && jobj.result.list.length) {
                          _this.success_action(jobj.result.list[0].table_id);
                        }
                      });
                    } else {
                      _this.$toast(json.result.tip, 'danger');
                    }
                  } else if (json.error) {
                    _this.$toast(json.error.message, 'danger');
                  } else {
                    _this.$toast('服务器请求失败！');
                  }
                });
              }
            }
          }
        }
      },
      /**
       * 获取某个表的详细信息
       * @param {Number} table_id 表ID
       */
      get_table(table_id) {
        if (this.form.table_id === table_id) {
          this.form.table_id = 0;
          this.list_field.map((o) => {
            o.table_id = 0;
            o.field_id = 0;
          });
        } else {
          var _this = this;
          this.$get("~/apis/dev/order_table?method=get_obj&", {
            table_id
          }, function(json) {
            if (json && json.result) {
              _this.form = json.result.obj;
              var config = _this.form.config;
              if (config) {
                _this.attr = Object.assign({}, _this.attr_defult, JSON.parse(config));
              } else {
                _this.attr = Object.assign({}, _this.attr_defult);
              }
              _this.get_field(_this.form.table_id)
            }
          });
        }
      },
      /**
       * 获取某表的字段
       * @param {Number} table_id 表ID
       */
      get_field(table_id, key = "list_field") {
        var _this = this;
        if (table_id) {
          this.$get("~/apis/dev/order_field?", {
            table_id,
            orderby: "display asc"
          }, function(json) {
            var res = json.result;
            if (res) {
              var list = res.list;
              if (list.length) {
                list.push(Object.assign({}, _this.field_defult, {
                  table_id
                }));
                _this[key] = list;
              } else {
                _this[key] = [Object.assign({}, _this.field_defult, {
                  table_id
                })];
              }
            }
          })
        } else {
          _this[key] = [Object.assign({}, _this.field_defult, {
            table_id
          })];
        }
      },
      /**
       * 创建过滤器
       * @param {String} keyword 关键词
       * @return {Function} 返回过滤函数
       */
      createFilter(keyword) {
        return (item) => {
          var value = item.title;
          return (value !== keyword && value.toLowerCase().indexOf(keyword.toLowerCase(keyword)) === 0);
        };
      },
      /**
       * 数据表搜索
       * @param {String} keyword 关键词
       * @param {Function} cb 回调函数
       */
      tableSearch(keyword, cb) {
        var results = keyword ? this.all_table.filter(this.createFilter(keyword)) : this.all_table;
        // 调用 callback 返回建议列表的数据
        cb(results);
      },
      /**
       * 获取所有表
       */
      get_all_table() {
        var _this = this;
        this.$get("~/apis/dev/order_table?method=count&groupby=title&field=title&orderby=count_title desc", {},
          function(json) {
            if (json && json.result) {
              _this.all_table = json.result.list;
            }
          });
      },
      /**
       * 选用表名
       * @param {Object} item 选项
       */
      handleSelect(item) {
        this.form.title = item.title;
        this.form.name = "";
        this.set_name();
      },
      /**
       * 智能匹配字段
       */
      auto_field() {
        var _this = this;
        this.$get("~/apis/dev/order_auto_field?", {
          table: this.form.name
        }, function(json) {
          var res = json.result;
          if (res) {
            var list = res.list;
            if (list.length) {
              list.push(Object.assign({}, _this.field_defult));
              _this.list_field = list;
            }
          } else if (res.error) {
            this.$toast(res.error.message);
          } else {
            this.$toast("服务器连接失败！");
          }
        })
      },
      /**
       * 获取某表的字段2
       * @param {Number} table_id 表ID
       */
      get_field2(table_id) {
        this.$get("~/apis/dev/order_field?", {
          table_id,
          orderby: "display asc"
        }, (json) => {
          var res = json.result;
          if (res.list) {
            this.list_field_refer = res.list;
          } else {
            this.list_field_refer = [];
          }
        });
      },
      /**
       * 设置字段属性
       * @param {Object} o
       */
      set_field2(o) {
        var list = this.list_field;
        var obj_filed = list[list.length - 1];
        $.push(obj_filed, o);
        list.push(Object.assign({}, this.field_defult))
        // this.obj = o.title;
        // this.obj = o.name;
        // document.activeElement; // 获取焦点元素
      }
    },
    created() {
      this.get_all_table();
    }
  }
</script>

<style scoped="scoped">
  .diy_mod {
    height: 75rem;
  }

  .el-tag {
    margin-right: .5rem;
  }

  .active {
    border-color: #409EFF;
  }

  #float_box {
    z-index: 1000;
    position: fixed;
    min-width: 8rem;
    top: 60%;
    left: 80%;
    padding: 0.5rem 1rem;
    border: 1px solid #dbdbdb;
    background-color: #fff;
    box-shadow: 0.5rem 0.25rem 0.25rem rgba(0, 0, 0, .1);
    border-radius: 0.5rem;
  }

  #float_box h5 {
    margin: 0.25rem;
  }

  #float_box i {
    position: relative;
    top: 0.25rem
  }

  #float_box .item:hover {
    background: rgba(0, 0, 0, 0.1);
  }
</style>
